// pages/FeiSu/fsDetail/fsDetail.js
import encode from '../../../utils/base64.js';
import request from '../../../utils/config.js';
import util from '../../../utils/util.js';
let WXBizDataCrypt = require('../../../utils/RdWXBizDataCrypt.js');
var wxCharts = require('../../../utils/wxcharts.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList: ['服务记录', '详情', '资料', '收支', '发票'],
    target_current:0,
    current:0,
    info:{},
    detailList: [],
    detailList2: [],
    detailList3: [],
    serviceList:[],
    projectAccounts1: [],
    projectAccounts2: [],
    projectInvoices:[],
    ifSlt: true,
    showDetail: false,
    showFile: false,
    isFromOpenDoc:false,
    showModel: false,
    projectId:'',
    showHomeBtn: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.projectId){
      this.setData({
        showHomeBtn: true,
        target_current: 0,
        projectId: options.projectId
        // ROLE_ServiceRecordManage: app.globalData.loginUserInfo.roles.indexOf('ROLE_ServiceRecordManage') != -1
      })
    }else{
      this.setData({
        target_current: options.current * 1,
        // ROLE_ServiceRecordManage: app.globalData.loginUserInfo.roles.indexOf('ROLE_ServiceRecordManage') != -1
      })
    }
  },


  onShow: function () {
    if (!wx.getStorageSync('token')) {
      //未登录
      wx.showModal({
        title: '未登录',
        content: '请先登录系统',
        confirmText: '前去登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../../index/index',
            })
          } else if (res.cancel) {
          }
        }
      })
      return
    }
    //判断案件进入的场景（列表进入、推送消息进入）
    if (app.globalData.userInfo && !this.data.projectId) {//列表进入
      this.setData({
        ChartSlt: false,
        ROLE_ServiceRecordManage: app.globalData.loginUserInfo.roles.indexOf('ROLE_ServiceRecordManage') != -1
      })
      if (this.data.isFromOpenDoc) {
        this.setData({ isFromOpenDoc: false })
      } else {
        this.get_projectBaseInfos()
      }
    } else {//消息推送
      // app.globalData.caseDetailData = {};
      let _that = this;
      if (!app.globalData.userInfo) {//判断是否登录过
        app.getAuthUserInfo((res) => {
          res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
          app.globalData.userInfo = res.userInfo;
          app.globalData.encryptedData = res.encryptedData;
          app.globalData.iv = res.iv;
          _that.getOpenid(_that);
        }, (res) => {
          _that.setData({
            showModel: true
          })
        });
      } else {//已登录
        //先还原赋值
        app.globalData.projectId = this.data.projectId;
        this.setData({
          ChartSlt: false,
          ROLE_ServiceRecordManage: app.globalData.loginUserInfo.roles.indexOf('ROLE_ServiceRecordManage') != -1
        })
        if (this.data.isFromOpenDoc) {
          this.setData({ isFromOpenDoc: false })
        } else {
          this.get_projectBaseInfos()
        }
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
    this.homeBtn = this.selectComponent("#homeBtn");
  },

  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    that.getOpenid(that);
  },

  //点击返回首页组件回调
  _goHomeBtn: function (e) {
    wx.setStorageSync("flagName", "nonLitigation");
    wx.redirectTo({
      url: '../fsIndex/fsIndex?flagName=nonLitigation'
    })
  },

  //获取openid
  getOpenid: (_that) => {
    app.getGlobalOpenid(function (token) {
      if (token) {
        //开始校验看token值
        _that.checkToken();
      } else {
        wx.hideLoading();
        //未登录
        wx.showModal({
          title: '未登录',
          content: '请先登录系统',
          confirmText: '前去登录',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
      }
    });
  },

  //检验token值
  checkToken: function () {
    let _that = this;
    app.checkGlobalToken(function (res) {
      _that.setData({
        loginUserInfo: res.loginUserInfo,
      });
      let tempList = res.tempList;
      let flagName = res.flagName;
      let jurisdiction = res.jurisdiction;
      let roleQuanxian = res.roleQuanxian;
      let department = res.department;
      if (tempList.length == 0) {
        wx.showModal({
          title: '对不起',
          content: '您的权限不足',
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return;
      }

      //校验上次记住的部门权限是否还存在
      if (jurisdiction.indexOf(roleQuanxian) < 0) {
        wx.showModal({
          title: '对不起',
          content: "您的" + department + "权限不足",
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return;
      }
      app.globalData.projectId = _that.data.projectId;
      _that.setData({
        ChartSlt: false,
        ROLE_ServiceRecordManage: app.globalData.loginUserInfo.roles.indexOf('ROLE_ServiceRecordManage') != -1
      })
      if (_that.data.isFromOpenDoc) {
        _that.setData({ isFromOpenDoc: false })
      } else {
        _that.get_projectBaseInfos()
      }
    }, function (res) {
      //登录超时
      wx.showModal({
        title: '登录超时',
        content: '点击确定重新登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../../index/index',
            })
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  swiperChange:function(e){
    // console.log(e)
    if (e.detail.source == "touch") {
      this.setData({current: e.detail.current })
    }
  },
  
  get_projectBaseInfos() {
    let _this = this;
    wx.showLoading({ title: ' ', mask: true })
    console.log('app.globalData.projectId', app.globalData.projectId)
    request.requestMisApi('get', "projectBaseInfos/" + app.globalData.projectId, {}, (res) => {
      if (res.code == '00') {
        let info = JSON.parse(res.body);
        console.log('projectBaseInfos', info)
        info.yujiyingshou = util.SYT_util.formatMoney(util.SYT_util.math.accDiv(info.expectReceivableMin * 1, 10000), 2) + "-" + util.SYT_util.formatMoney(util.SYT_util.math.accDiv(info.expectReceivableMax * 1, 10000), 2);
        info.operTimeStr = util.timetrans(info.operTime, 'day')
        _this.getProjectServiceList();
        let detailList = [
          {
            name: '项目ID',
            value: info.projectId != null ? info.projectId : ''
          },{
            name: '项目类型',
            value: info.projectTypeIdDesc != null ? info.projectTypeIdDesc : ''
          },{
            name: '项目名称',
            value: info.projectName != null ? info.projectName : ''
          },{
            name: '当事人',
            value: info.litigant != null ? info.litigant : ''
          },{
            name: '对方当事人',
            value: info.opposLitigant != null ? info.opposLitigant : ''
          },{
            name: '签约律所',
            value: info.companyName != null ? info.companyName : ''
          },{
            name: '地址',
            value: info.address != null ? info.address : ''
          },{
            name: '固定电话',
            value: info.tel != null ? info.tel : ''
          },{
            name: '联系人',
            value: info.linkman != null ? info.linkman : ''
          },{
            name: '手机号',
            value: info.mobileNo != null ? info.mobileNo : ''
          },{
            name: '邮箱',
            value: info.email != null ? info.email : ''
          }
        ]
        let detailList2 = [
          {
            name: '案件标的',
            value: info.caseAmt != null ? info.caseAmt : ''
          },{
            name: '本金',
            value: info.capitalAmt != null ? info.capitalAmt : ''
          },{
            name: '利息/违约金',
            value: info.interestAmt != null ? info.interestAmt : ''
          },{
            name: '前期收入',
            value: info.preIncomeAmt != null ? info.preIncomeAmt : ''
          },{
            name: '预计应收区间值',
            value: (info.expectReceivableMin != null && info.expectReceivableMax != null )? util.SYT_util.formatMoney(util.SYT_util.math.accDiv(info.expectReceivableMin * 1, 10000), 2) + "-" + util.SYT_util.formatMoney(util.SYT_util.math.accDiv(info.expectReceivableMax * 1, 10000), 2): ''
          },{
            name: '案由',
            value: info.caseTypeDesc != null ? info.caseTypeDesc : ''
          },{
            name: '部门',
            value: info.deptName != null ? info.deptName : ''
          },{
            name: '签约日期',
            value: info.signDate != null ? util.dateStr(info.signDate) : ''
          },{
            name: '状态',
            value: info.statusDesc != null ? info.statusDesc : ''
          },{
            name: '操作时间',
            value: info.operTime!= null ? util.timetrans(info.operTime) : ''
          }
        ]
        let detailList3 = [
          {
            name: '累计预支',
            value: info.sumAdvanceAmt != null ? info.sumAdvanceAmt:''
          },{
            name: '当前预支',
            value: info.currAdvanceAmt != null ? info.currAdvanceAmt : ''
          },{
            name: '垫资应收金额',
            value: info.receivableAmt != null ? info.receivableAmt : ''
          },{
            name: '费用',
            value: info.costAmt != null ? info.costAmt : ''
          },{
            name: '收入',
            value: info.incomeAmt != null ? info.incomeAmt : ''
          },{
            name: '开票金额',
            value: info.invoiceAmt != null ? info.invoiceAmt : ''
          }
        ]
        info.manageInfo = [];
        if (info.manageInfoList && info.manageInfoList.length > 0) {
          info.manageInfoList.forEach((item2) => {
            if (item2.lawyerRole == '1') {
              info.manageInfo.unshift(item2.lawyerName)
            } else {
              info.manageInfo.push(item2.lawyerName)
            }
          })
        }
        if (info.manageInfo.length > 0) {
          info.manageInfo = info.manageInfo.toString();
        } else {
          info.manageInfo = ''
        }
        info.manageInfo = info.manageInfo.replace(/,/g, '、');
        info.favorImg = info.isFavor=="Y"?'heart_slt':'heart'
        _this.setData({ info: info,detailList: detailList, detailList2: detailList2, detailList3: detailList3})
      }
    }, (res) => {
      _this.getProjectServiceList();
      console.log("接口错误=", res)
    });
  },
  getProjectServiceList:function(){
    let _this = this;
    request.requestMisApi('get', "projectServicesRecord", { body: { projectId: app.globalData.projectId}}, (res) => {
      wx.hideLoading();
      if (res.code == '00') {
        let info = JSON.parse(res.body);
        info.forEach((item) => {
          item.serviceDateStr = util.dateStr(item.serviceDate);
          item.showDetail = false;
          item.docList.forEach((item2) => {
            item2.docName = item2.docUrl.replace(app.globalData.ossUrlPre, '').replace(/[A-Z|A-z|2-8]{10}/, '');
            item2.iconImg = util.getDocIconImg(item2.docUrl);
            item2.canOpen = util.getDocCanOpen(item2.docUrl)
          })
        })
        console.log('projectServicesRecord', info)
        _this.setData({ serviceList: info})
      }
      _this.getprojectAccounts1()
    }, (res) => {
      wx.hideLoading();
      _this.getprojectAccounts1()
      console.log("接口错误=", res)
    });
  },
  getprojectAccounts1: function () {
    let _this = this;
    request.requestMisApi('get', "projectAccounts/income", { projectId: app.globalData.projectId}, (res) => {
      if (res.code == '00') {
        let info = JSON.parse(res.body);
        info.forEach((item) => {
          item.operTimeStr = util.dateStr(item.operDate);
          item.showFile = false;
          item.docList.forEach((item2) => {
            item2.docName = item2.docUrl.replace(app.globalData.ossUrlPre, '').replace(/[A-Z|A-z|2-8]{10}/, '');
            item2.iconImg = util.getDocIconImg(item2.docUrl);
            item2.canOpen = util.getDocCanOpen(item2.docUrl)
          })
          if (item.incomeDesc && item.incomeDesc.length>3){
            item.incomeDesc3 = item.incomeDesc.substr(0, 3) + '...';
          }else{
            item.incomeDesc3=false
          }
          item.incomeDesc3slt = false;
        })
        console.log('projectAccounts1', info)
        _this.setData({ projectAccounts1: info })
      }
      if (_this.data.target_current == 3) {
        _this.setData({ current: 3, target_current:0 })
      }
      _this.getprojectAccounts2();
    }, (res) => {
      _this.getprojectAccounts2();
      console.log("接口错误=", res)
    });
  },
  getprojectAccounts2: function () {
    let _this = this;
    request.requestMisApi('get', "projectAccounts", { projectId: app.globalData.projectId }, (res) => {
      if (res.code == '00') {
        let info = JSON.parse(res.body);
        info.forEach((item) => {
          item.operTimeStr = util.dateStr(item.operDate);
          item.showFile = false;
          item.docList.forEach((item2) => {
            item2.docName = item2.docUrl.replace(app.globalData.ossUrlPre, '').replace(/[A-Z|A-z|2-8]{10}/, '');
            item2.iconImg = util.getDocIconImg(item2.docUrl);
            item2.canOpen = util.getDocCanOpen(item2.docUrl)
          })
        })
        console.log('projectAccounts2', info)
        _this.setData({ projectAccounts2: info })
      }
      if (_this.data.target_current == 3) {
        _this.setData({ current: 3, target_current: 0 })
      }
      _this.getprojectDocs();
    }, (res) => {
      _this.getprojectDocs();
      console.log("接口错误=", res)
    });
  },
  getprojectDocs:function () {
    let _this = this;
    request.requestMisApi('get', "projectDocs/" + app.globalData.projectId, {}, (res) => {
      if (res.code == '00') {
        let info = JSON.parse(res.body), docList = [], reportDocList = [];
        info.forEach((item) => {
          item.docName = item.docUrl.replace(app.globalData.ossUrlPre, '').replace(/[A-Z|A-z|2-8]{10}/, '');
          item.iconImg = util.getDocIconImg(item.docUrl);
          item.canOpen = util.getDocCanOpen(item.docUrl)
          if (item.docKindDesc =='项目资料'){
            docList.push(item)
          } else if (item.docKindDesc == '项目报告') {
            reportDocList.push(item)
            console.log('项目报告列表长度============', reportDocList)
          }
        })
        // console.log('projectServicesRecord', info)
        _this.setData({
          docList: docList,
          reportDocList: reportDocList,
        })
      }
      _this.getprojectInvoices()
    }, (res) => {
      _this.getprojectInvoices()
      console.log("接口错误=", res)
    });
  },
  getprojectInvoices: function () {
    let _this = this;
    request.requestMisApi('get', "projectInvoices/" + app.globalData.projectId,{}, (res) => {
      if (res.code == '00') {
        let info = JSON.parse(res.body);
        console.log('projectInvoices', info)
        info.forEach((item) => {
          item.invoiceDateStr = util.dateStr(item.invoiceDate);
        })
        _this.setData({ projectInvoices: info })
      }
    }, (res) => {
      console.log("接口错误=", res)
    });
  },
  favor:function(){
    let info = this.data.info;
    if (info.favorImg == 'heart_slt') {
      info.favorImg = 'heart'
      let _this = this;
      request.requestMisApi("get", "flyWorkPlace/unfavorProjects/" + app.globalData.projectId, {}, (res) => {
        console.log("收藏", res)
      }, (res) => {
        console.log("收藏失败", res)
      });
    } else {
      info.favorImg = 'heart_slt';
      let _this = this;
      request.requestMisApi("get", "flyWorkPlace/favorProjects/" + app.globalData.projectId, {}, (res) => {
        console.log("收藏", res)
      }, (res) => {
        console.log("收藏失败", res)
      });
    }
    this.setData({ info })
  },
  clickTab: function(e) {
    this.setData({
      current: e.currentTarget.dataset.index,
    })
  },
  goChart: function () {
    this.setData({
      ChartSlt: true,
    })
    wx.navigateTo({
      url: '../chart/chart?projectId=' + app.globalData.projectId,
    })
  },
  toggleDetail: function (e) {
    let serviceList = this.data.serviceList;
    let index = e.currentTarget.dataset.index;
    serviceList[index].showDetail = !serviceList[index].showDetail
    this.setData({
      serviceList: serviceList
    })
  },
  addClientMsg: function () {
    wx.navigateTo({
      url: '../addMsg/addMsg?projectId=' + app.globalData.projectId + '&lawyers=' + JSON.stringify(this.data.info.manageInfoList) + '&projectTypeId=' + this.data.info.projectTypeId,
    })
  },

  closeMsg: function() {
    this.setData({
      showAddMsg: false
    })
  },
  toggleFileList1: function(e) {
    let projectAccounts1 = this.data.projectAccounts1;
    let index = e.currentTarget.dataset.index;
    projectAccounts1[index].showFile = !projectAccounts1[index].showFile
    this.setData({
      projectAccounts1: projectAccounts1
    })
  },
  toggleFileList2: function (e) {
    let projectAccounts2 = this.data.projectAccounts2;
    let index = e.currentTarget.dataset.index;
    projectAccounts2[index].showFile = !projectAccounts2[index].showFile
    this.setData({
      projectAccounts2: projectAccounts2
    })
  },
  toggleMemo1: function (e) {
    let projectAccounts1 = this.data.projectAccounts1;
    let index = e.currentTarget.dataset.index;
    projectAccounts1[index].incomeDesc3slt = !projectAccounts1[index].incomeDesc3slt
    this.setData({
      projectAccounts1: projectAccounts1
    })
  },
  docClick(e) {
    let doc = e.currentTarget.dataset.doc
    if (doc.canOpen) {
      this.dowmloadFile(doc.docUrl, doc.docName)
    } else {
      wx.setClipboardData({
        data: doc.docUrl,
        success: function (res) {
          console.log(res)
          wx.showToast({
            title: '复制链接成功',
            icon: 'success',
            duration: 700
          })
          setTimeout(() => {
            wx.showModal({
              content: '该文件无法预览，文件路径已复制到剪切板，你可以打开浏览器下载',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }, 700)
        }
      })
    }
  },
  docLongpress: function (e) {
    let doc = e.currentTarget.dataset.doc
    wx.setClipboardData({
      data: doc.docUrl,
      success: function (res) {
        console.log(res)
        wx.showToast({
          title: '复制链接成功',
          icon: 'success',
          duration: 800
        })
      }
    })
  },
  //点击下载文件
  dowmloadFile: function (fileurl, docName) {
    let _this=this;
    let tempSuf = docName.split('.');
    let suffix = tempSuf[tempSuf.length - 1];
    let fileType = "doc,xls,ppt,pdf,docx,xlsx,pptx";
    let picSuffix = "bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,jpeg";
    console.log("fileurl==", fileurl, docName)
    wx.showLoading({ title: ' ', mask: true })
    wx.downloadFile({
      url: fileurl, //仅为示例，并非真实的资源
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log("读取文件成功=", res)
        // if (res.statusCode === 200) {
        var filePath = res.tempFilePath
        wx.hideLoading()
        _this.setData({ isFromOpenDoc: true })
        if (fileType.indexOf(suffix) != "-1") {
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        } else if (picSuffix.indexOf(suffix.toLowerCase()) != "-1") {
          wx.previewImage({
            current: filePath, // 当前显示图片的http链接
            urls: [filePath] // 需要预览的图片http链接列表
          })
        }
      },
      fail: function (res) {
        wx.hideLoading()
        console.log("读取文件失败=", res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  //转发
  // onShareAppMessage: function (res) {
  //   if (res.from === 'button') {
  //     // 来自页面内转发按钮
  //     console.log("来自页面内的转发", res.target)
  //   }
  //   let This = this;
  //   console.log("pages/FeiSu/fsDetail/fsDetail?projectId=", app.globalData.projectId)
  //   return {
  //     title: "转发测试",
  //     path: 'pages/FeiSu/fsDetail/fsDetail?projectId=' + app.globalData.projectId,

  //     success: function (res) {
  //       // 转发成功
  //       console.log("转发成功返回数据=", res)
  //       wx.showShareMenu({
  //         // 要求小程序返回分享目标信息
  //         withShareTicket: true
  //       });

  //       if (res.shareTickets) {
  //         // 获取转发详细信息
  //         wx.getShareInfo({
  //           shareTicket: res.shareTickets[0],
  //           success(res) {

  //           },
  //           fail() { },
  //           complete() { }
  //         });
  //       }
  //     },
  //     fail: function (res) {
  //       // 转发失败
  //     },
  //     complete: function () {

  //     }
  //   }
  // },
})